package com.frxuexi.cart.view

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.Gravity
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.PopupWindow
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.ToastUtils
import com.frxuexi.cart.R
import com.frxuexi.cart.adapter.OrderAdapter
import com.frxuexi.cart.databinding.ActivityOrderBinding
import com.frxuexi.cart.databinding.PopTuiBinding
import com.frxuexi.cart.viewmodel.CartViewModel
import com.frxuexi.lib_base.alipay.MyPay
import com.frxuexi.lib_base.entity.OrderBeanItem
import com.frxuexi.lib_base.entity.PayOrderReqBean
import com.frxuexi.lib_base.mvvm.BaseActivity
import com.frxuexi.lib_base.utils.ArouterManager
import com.frxuexi.lib_base.utils.GlideUtils
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayout.OnTabSelectedListener
import dagger.hilt.android.AndroidEntryPoint
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

@AndroidEntryPoint
@Route(path = "/cart/OrderActivity")
class OrderActivity : BaseActivity<ActivityOrderBinding,CartViewModel>() {
    val orderAdapter by lazy { OrderAdapter() }
    lateinit var order:OrderBeanItem
    var tabPos=0
    lateinit var window:PopupWindow
    override fun initData() {
        vm.cartError.observe(this){
            ToastUtils.showLong(it)
        }
        vm.orderData.observe(this){
            it.list.forEach {
                if(it.orderStatus=="待支付"){
                    it.myType=0
                }else if (it.orderStatus=="待发货"){
                    if(tabPos==3){
                        it.myType=3
                    }else {
                        it.myType = 1
                    }
                }
                else if (it.orderStatus=="待收货"){
                    it.myType=2
                }else if (it.orderStatus=="待评价"){
                    it.myType=3
                }else if (it.orderStatus=="已完成"){
                    it.myType=4
                }else{
                    it.myType=5
                }
            }
            orderAdapter.apply {
                data.clear()
                addData(it.list)
                notifyDataSetChanged()
            }
        }

        vm.payOrderData.observe(this){
            ToastUtils.showLong("支付成功")
            vm.getOrders(1,"0")
        }

        vm.cancelOrderData.observe(this){
            vm.getOrders(1,tabPos.toString())
        }

        vm.outOrderData.observe(this){
            ToastUtils.showLong("退款成功")
            window.dismiss()
        }

    }

    override fun initView() {
//        注册EventBus
        EventBus.getDefault().register(this)
        binding.orderTab.apply {
            addTab(newTab().setText("未支付"),true)
            addTab(newTab().setText("待发货"))
            addTab(newTab().setText("待收货"))
            addTab(newTab().setText("待评价"))
            addTab(newTab().setText("已完成"))
            addTab(newTab().setText("售后/退货"))
//            订单状态的tab选中事件
            addOnTabSelectedListener(object :OnTabSelectedListener{
                override fun onTabSelected(tab: TabLayout.Tab?) {
//                    点击的tab的item的索引
                    tabPos=tab?.position!!
                    when(tab?.position){
                        5->vm.getOrders(1,"-3")
                        3->vm.getOrders(1,"1")
                        else->vm.getOrders(1,tab?.position.toString())
                    }
                }

                override fun onTabUnselected(tab: TabLayout.Tab?) {

                }

                override fun onTabReselected(tab: TabLayout.Tab?) {

                }
            })
        }
        binding.orderRv.apply {
            adapter=orderAdapter
            layoutManager=LinearLayoutManager(this@OrderActivity)
        }

//        页面进来先查询未支付的订单列表
        vm.getOrders(1,"0")

        orderAdapter.addChildClickViewIds(R.id.order_pay,R.id.order_cancel,R.id.order_comment,R.id.order_tui)
        orderAdapter.setOnItemChildClickListener { adapter, view, position ->
            order = orderAdapter.data.get(position)
            when(view.id){
                R.id.order_pay->{
                    //支付流程：支付宝支付-调支付接口更改支付状态
//                    1.支付宝支付
                    MyPay.payV2(order.payPrice,this)
                }
                R.id.order_cancel->{
                    vm.cancelOrder(order.id)
                }
                R.id.order_comment->{
                    ARouter.getInstance().build("/cart/CommentAddActivity").withInt("id",order.orderInfoList.get(0).productId).withString("no",order.orderId).navigation()
                }
                R.id.order_tui->{
//                    获取一个popupWindow,设置宽高
                    window = PopupWindow(ViewGroup.LayoutParams.MATCH_PARENT, 1000)
//                    获取popupWindow的binding
                    val tuiBinding = PopTuiBinding.inflate(LayoutInflater.from(this))
//把页面设置到窗口上
                    window.contentView=tuiBinding.root
//窗口显示
                    window.showAtLocation(view,Gravity.BOTTOM,0,0)
                    tuiBinding.bean=order
                    GlideUtils.getRoundImage(tuiBinding.tuiIv,order.orderInfoList.get(0).image)
//点击X,关闭窗口
                    tuiBinding.tuiClose.setOnClickListener {
                        window.dismiss()
                    }

                    tuiBinding.tuiBtn.setOnClickListener {
                        vm.outOrder(mapOf("id" to order.id,"text" to "不好","uni" to order.orderId))
                    }
                }
            }
        }
    }

//    EventBus接收内容
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun getMsg(msg:String){
        if(msg=="payOk"){
            Log.i("lr",msg)
//            2.调支付接口更改支付状态
            val reqBean =
                PayOrderReqBean("", order.orderId, "alipay", "yue", 0, order.id.toString())
            vm.payOrder(reqBean)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }

}